public class NumMatrix {

    int[][] matrix;
    int[][] dp;
    public NumMatrix(int[][] matrix) {
        this.matrix = matrix;
        if (matrix.length != 0) {
            dp = new int[matrix.length][matrix[0].length];
            for (int i = 0; i < matrix.length; i++) {
                dp[i][0] = matrix[i][0];
            }
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 1; j < matrix[0].length; j++) {
                    dp[i][j] = dp[i][j - 1] + matrix[i][j];
                }
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for (int i = row1; i < row2 + 1; i++) {
            sum += dp[i][col2] - dp[i][col1] + matrix[i][col1];
        }
        return sum;
    }
}
